package com.rdc.dictionary.adapter;


import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.rdc.dictionary.R;
import com.rdc.dictionary.application.App;
import com.rdc.dictionary.bean.Word;
import com.rdc.dictionary.search.SearchActivity;
import com.rdc.dictionary.vocabulary.VocabularyActivity;

import java.util.List;

import static androidx.core.content.ContextCompat.startActivity;

/**
 * @author Soul Mate
 * @file 文件名
 * @brief 单词的适配器
 */

public class WordsAdapter extends RecyclerView.Adapter<WordsAdapter.ViewHolder>
{
	private List<Word> mWordsList;

	//回调监听
	private NewWordOnItemClickListener listener;



	static class ViewHolder extends RecyclerView.ViewHolder
	{
		//单词名
		TextView wordName;

		//删除
		ImageView delete;

		public ViewHolder(View view)
		{
			super(view);
			wordName = (TextView) view.findViewById(R.id.tv_word_list_item);
			delete = (ImageView) view.findViewById(R.id.iv_delete_new);
		}

	}


	//new的时候设置回调
	public WordsAdapter(List<Word> wordList , NewWordOnItemClickListener listener)
	{
		mWordsList = wordList;
		this.listener = listener;
	}



	@NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
	{
		View view = LayoutInflater.from(parent.getContext())
				.inflate(R.layout.vocabulary_item, parent, false);
		ViewHolder holder = new ViewHolder(view);

		//监听单词点击事件
		holder.wordName.setOnClickListener(new View.OnClickListener()
		{
			@Override public void onClick(View v)
			{
				//得到点击位置
				int position =holder.getAdapterPosition();
				Word word = mWordsList.get(position);

				//切换到单词翻译界面并传递数据
				Intent intent = new Intent(App.sContext, SearchActivity.class);
				intent.putExtra("word_data",word);

			    //在非activity类中调用startActivity
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				App.sContext.startActivity(intent);
			}
		});


		//监控删除点击事件
		holder.delete.setOnClickListener(new View.OnClickListener()
		{
			@Override public void onClick(View v)
			{
				//得到点击位置
				int position =holder.getAdapterPosition();

				listener.onClickDelete(position);
			}
		});


		return holder;
	}





	@Override public void onBindViewHolder(@NonNull ViewHolder holder, int position)
	{

		Word word = mWordsList.get(position);
		holder.wordName.setText(word.getWord());
	}

	@Override public int getItemCount()
	{
		return mWordsList.size();
	}


	/**
	 * @author Soul Mate
	 * @file 文件名
	 * @brief 点击子项回调的外部接口。在外部定义所需实现的方法
	 */
	public interface NewWordOnItemClickListener
	{
		void onClickDelete(int position);
	}

}
